package com.fulihui.usercore.service;

import com.fulihui.usercore.api.UnionidOpenidService;
import com.fulihui.usercore.biz.conv.UnionidOpenidConv;
import com.fulihui.usercore.dal.dataobj.UnionidOpenidDO;
import com.fulihui.usercore.dal.mapper.UnionidOpenidMapper;
import com.fulihui.usercore.dto.UnionidOpenidDTO;
import com.fulihui.usercore.request.user.UnionidOpenidBatchInsertRequest;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.CommonServiceErrorEnum;
import org.near.servicesupport.error.InvokeServiceException;
import org.near.servicesupport.result.BaseResult;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.result.TMultiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @see UnionidOpenidService
 * @author Created by Willard.Hu on 2016/8/17 0017.
 */
@Service(version = "1.0.0")

public class UnionidOpenidServiceImpl implements UnionidOpenidService {
    @Autowired
    private UnionidOpenidMapper unionidOpenidMapper;

    /**
     * @see UnionidOpenidService#batchInsert(UnionidOpenidBatchInsertRequest)
     */
    @Override
    public BaseResult batchInsert(UnionidOpenidBatchInsertRequest request) {
        if (CollectionUtils.isEmpty(request.getList()) || request.getList().size() > 100) {
            throw new InvokeServiceException(CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        List<UnionidOpenidDO> items = request.getList().stream().map(UnionidOpenidConv::conv2DO)
            .collect(Collectors.toList());
        unionidOpenidMapper.insert(items);

        return ResultBuilder.succ(BaseResult.class);
    }

    /**
     * @see UnionidOpenidService#query(UnionidOpenidBatchInsertRequest)
     */
    @Override
    public TMultiResult<UnionidOpenidDTO> query(UnionidOpenidBatchInsertRequest request) {
        if (CollectionUtils.isEmpty(request.getList()) || request.getList().size() > 100) {
            throw new InvokeServiceException(CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        List<UnionidOpenidDTO> rs = Collections.emptyList();
        if (!CollectionUtils.isEmpty(request.getList())) {
            List<String> unionids = request.getList().stream().map(UnionidOpenidDTO::getUnionid)
                .collect(Collectors.toList());
            List<UnionidOpenidDO> doList = unionidOpenidMapper.query(unionids);
            if (!CollectionUtils.isEmpty(doList)) {
                rs = doList.stream().map(UnionidOpenidConv::conv2DTO).collect(Collectors.toList());
            }
        }
        return ResultBuilder.succTMulti(rs);
    }

}
